package com.example.springboot.pdf.utils;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author wangsh
 * @Title: 通过itextpdf工具类将word转为pdf
 * @Package ${package_name}
 * @Des: ${todo}
 * @date 2018/8/10 0010下午 4:42
 */
public class PDFUtils {
    //解析器key
    private static final String PARSER_KEY = "javax.xml.parsers.DocumentBuilderFactory";
    //    解析器值
    private static final String PARSER_VAL = "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl";
    //    Windows路径PDF生成字体
    private static final String BASE_FONT_WIN = "C:/WINDOWS/Fonts/SIMSUN.TTC,1";
    //    其他路径PDF生成字体
    private static final String BASE_FONT_OTHER = "C:/WINDOWS/Fonts/SIMSUN.TTC,1";

    /**
     * 设置pdf下载请求头信息
     *
     * @param response：响应对象
     * @param filename：文件名
     * @throws Exception
     */
    public static void setResponseHeader(HttpServletResponse response, String filename) throws Exception {
        // 指定解析器
        System.setProperty(PARSER_KEY, PARSER_VAL);
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
    }

    /**
     * 将word转为pdf
     *
     * @param os:输出流
     * @param filePath：文件全路径
     * @param data：填充pdf数据
     */
    public static void convertWord2Pdf(OutputStream os, String filePath, Map<String, Object> data) {

        PdfStamper ps = null;
        PdfReader reader = null;
        try {
            // 2 读入pdf表单
            reader = new PdfReader(filePath);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            // 5给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
            BaseFont bf = BaseFont.createFont(BASE_FONT_WIN, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);

            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null)
                    ps.close();
                if (reader != null)
                    reader.close();
                if (os != null)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 将word,图片转为pdf
     *
     * @param os
     * @param filePath
     * @param data
     */
    public static void convertWordImage2Pdf(OutputStream os, String filePath, Map<String, Object> data, List<Map<String, Object>> imageList) {

        PdfStamper ps = null;
        PdfReader reader = null;
        try {
            // 2 读入pdf表单
            reader = new PdfReader(filePath);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            // 5给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
            BaseFont bf = BaseFont.createFont(BASE_FONT_WIN, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);

            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }
            ps.setFormFlattening(true);


            //-----------------------------pdf 添加图片----------------------------------
            // 通过域名获取所在页和坐标，左下角为起点
            System.out.println("pdf 添加图片");
            if (imageList != null && imageList.size() > 0) {
                for (Map map : imageList) {
                    String imgpath = map.get("FileUrl").toString();
                    String imageName = map.get("imageName").toString();

                    if (form.getFieldPositions("PictureType" + imageName) != null && imgpath != null && !imageName.equals("")) {
                        //获取pdf中填充图片的x,y坐标位置
                        int pageNo = form.getFieldPositions("PictureType" + imageName).get(0).page;
                        Rectangle signRect = form.getFieldPositions("PictureType" + imageName).get(0).position;
                        float x = signRect.getLeft();
                        float y = signRect.getBottom();
                        // 读图片
                        Image image = Image.getInstance(imgpath);
                        // 获取操作的页面
                        PdfContentByte under = ps.getOverContent(pageNo);
                        // 根据域的大小缩放图片
                        image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                        // 添加图片
                        image.setAbsolutePosition(x, y);
                        under.addImage(image);
                    }
                }
            }
            //-------------------------------------------------------------
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ps != null)
                    ps.close();
                if (reader != null)
                    reader.close();
                if (os != null)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static BaseFont getBaseFont(String path) {
        BaseFont bf = null;
        try {
            String property = System.getProperty("os.name");
            if (StringUtils.isNotBlank(property)) {
                if ("Windows".equalsIgnoreCase(property)) {
                    path = BASE_FONT_WIN;
                } else if ("Linux".equalsIgnoreCase(property)) {
                    path = BASE_FONT_OTHER;
                }
            } else {
                path = BASE_FONT_WIN;
            }
            bf = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bf;
    }
}
